<template>
  <default-home-card icon="PieChartOutlined" title="品类统计">
    <div class="echarts-box">
      <div class="pie-main" id="pie-main"></div>
    </div>
  </default-home-card>
</template>
<script setup lang="ts">
import DefaultHomeCard from '@/views/system/home/components/default-home-card.vue'
import * as echarts from 'echarts'
import { onMounted } from 'vue'
import { homeApi } from '@/api/system/home-api'
onMounted(() => {
  init()
})

async function init() {
  let option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      top: 1,
      right: 50,
      orient: 'vertical',
      textStyle: {
        color: '#000'
      },
      formatter: function (name) {
        const seriesData = option.series[0].data.find((item) => item.name === name)
        return `${name} | ${seriesData.percentage.toFixed(2)}%`
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['55%', '80%'],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      },
      {
        name: '总计',
        type: 'pie',
        radius: '30%',
        center: ['30%', '50%'],
        label: {
          show: true,
          position: 'center',
          formatter: () => {
            return `{titleStyle|库存总货值（元）}\n\n{valueStyle|¥ ${total.toLocaleString()}}`
          },
          rich: {
            titleStyle: {
              fontSize: 14,
              fontWeight: 'normal',
              color: '#666'
            },
            valueStyle: {
              fontSize: 18,
              fontWeight: 'bold',
              color: '#333'
            }
          }
        },
        itemStyle: {
          normal: {
            color: 'rgba(0,0,0,0)'
          }
        },
        data: [
          {
            value: 0,
            name: ''
          }
        ]
      }
    ]
  }
  const data = await homeApi.stockStatistics()
  option.series[0].data = data.data.category_stats.map((item) => {
    return {
      value: item.inventory_value,
      name: item.category_name,
      percentage: item.percentage
    }
  })

  const total = data.data.total_inventory_value
  option.series[1].data[0].value = total

  let chartDom = document.getElementById('pie-main')
  if (chartDom) {
    let myChart = echarts.init(chartDom)
    option && myChart.setOption(option)
  }
}
</script>
<style lang="less" scoped>
.echarts-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 286px;
  .pie-main {
    width: 100%;
    height: 260px;
    background: #fff;
  }
}
</style>
